﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OutOfUnity
{
    public class ObjectPool<T> where T : new()
    {
        private static ObjectPool<T> instance_;
        private static readonly object lockHolder = new object();
        private ConcurrentBag<T> objects_;
        public static ObjectPool<T> Instance
        {
            get
            {
                if (instance_ == null)
                {
                    lock (lockHolder)
                    {
                        if (instance_ == null)
                        {
                            instance_ = new ObjectPool<T>();
                        }
                    }
                }
                return instance_;
            }
        }
        public ObjectPool()
        {
            objects_ = new ConcurrentBag<T>();
        }
        public T GetObject()
        {
            T item;
            if (objects_.TryTake(out item))
            {
                return item;
            }
            return new T();
        }
        public void PutObject(T item)
        {
            objects_.Add(item);
        }
    }
}
